﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;

// taken from http://fastjson.codeplex.com/ LGPL 2.1
using fastJSON;

using WebSockets.Net;
using WebSockets.Utils;

using MtGox.Types;

class Program
{
	public static void Main( string[] args )
	{
		// we interested
		var lcs = new List<Currency>();
		lcs.Add( Currency.USD );
		lcs.Add( Currency.EUR );
		var cs = ParseCurrencies( lcs );

		// socket.io doesnt work for now - I'm too lazy to debug it
		//mtgoxSocketIoImpl();

		// NB:
		// websocket works for now (YMD=2013.04.01) BUT ...
		/*
		 * here https://en.bitcoin.it/wiki/MtGox/API/Streaming written
		 * >The session ID expires after 30 seconds
		 * but session continues ~5-60min followed by FIN
		 */
		mtgoxWebSocketImpl( cs );

		Console.WriteLine( "\nPress [ENTER] for exit\n\n" );
		Console.ReadLine();
	}

	static string ParseCurrencies( IList<Currency> currs )
	{
		var sb = new StringBuilder();
		foreach (var ec in currs)
		{
			if (sb.Length > 0)
				sb.Append( ',' );
			sb.Append( ec );
		}
		return sb.ToString();
	}

	#region MtGox socket.io impl - doesnt work :(
	static SocketIO _sio;
	static void mtgoxSocketIoImpl()
	{
		_sio = new SocketIO();
		_sio.OnMessage += onMessage;
		_sio.OnJson += onJson;
		_sio.Open( @"https://socketio.mtgox.com/mtgox?Currency=USD", Encoding.ASCII );

		// send raw JSON-messages into WebSocket
		_sio.WebSocket.SendAscii( "4:::{\"op\":\"mtgox.subscribe\",\"type\":\"trades\"}" );
		_sio.WebSocket.SendAscii( "4:::{\"op\":\"mtgox.subscribe\",\"type\":\"ticker\"}" );
		_sio.WebSocket.SendAscii( "4:::{\"op\":\"mtgox.subscribe\",\"type\":\"depth\"}" );
	}

	static void onMessage( string msg, int? msgId, string ep )
	{
		Console.WriteLine( "MESSAGE: " + msg );
	}

	static void onJson( string json, int? msgId, string ep )
	{
		var obj = JSON.Instance.ToObject<Packet>( json );
		Console.WriteLine( "JSON: " + obj );
	}
	#endregion

	#region MtGox WebSocket impl
	static WebSocket _wsock;
	static void mtgoxWebSocketImpl( string currs )
	{
		_wsock = new WebSocket( Encoding.ASCII );
		_wsock.OnString += onString;
		_wsock.OnClosed += (ws) => Console.WriteLine( "FIN" );

		var url = "ws://websocket.mtgox.com/mtgox";
		if (!string.IsNullOrEmpty( currs ))
			url += "?Currency=" + currs;
		_wsock.Open( url );
	}

	static void onString( WebSocket ws, string json )
	{
		var obj = JSON.Instance.ToObject<Packet>( json );

		if (obj.depth != null)
			Console.ForegroundColor = ConsoleColor.DarkGreen;
		else if (obj.trade != null)
			Console.ForegroundColor = ConsoleColor.Yellow;
		else
			Console.ForegroundColor = ConsoleColor.Magenta;

		Console.WriteLine( obj );
	}
	#endregion 
}
